﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using AngleSharp.Html.Parser;
using Newtonsoft.Json.Linq;
using Tool.Expansion;
using Tool.Web.HttpHelper;
using static Core.Common.Global;

namespace Core.Function
{
	public static class Anime
	{
		static readonly Type typeMshtml = Type.GetTypeFromCLSID(new Guid("{25336920-03F9-11CF-8FD0-00AA00686F13}"));
		static readonly HtmlParser parser = new HtmlParser();

		internal class AnimeInfo
		{
			public string name { get; set; }
			public string url { get; set; }
		}

		internal class SearchResult
		{
			public bool ready { get; set; }
			public long qq { get; set; }
			public List<AnimeInfo> animeInfos { get; set; }
		}

		public static string GetList(string key, long qq)
		{
			//https://www.agefans.tv/search?query=%E6%81%B6%E9%AD%94
			var url = "http://www.yxdm.me/search.html?title=" + Url.Decode(key, Encoding.UTF8);
			var html = HttpNet.Get(url);
			if (html.Length == 0) return "搜索失败";
			var searlist = parser.ParseDocument(Encoding.UTF8.GetString(html));
			var dhnew = searlist.QuerySelector("div.dhnew");
			List<AnimeInfo> animeInfos = new List<AnimeInfo>();
			StringBuilder stringBuilder = new StringBuilder(255);
			stringBuilder.Append("搜索到以下结果");
			int i = 1;
			foreach (var item in dhnew.QuerySelectorAll("li"))
			{
				var a = item.QuerySelector("a");
				var info = new AnimeInfo();
				info.url = a.Attributes["href"].Value;
				info.name = a.Attributes["title"].Value;
				animeInfos.Add(info);
				stringBuilder.Append("\r\n" + i + "：" + info.name);
				i++;
			}
			stringBuilder.Append("\r\n请回复序号选择");
			hashTable["番剧搜索" + qq] = new SearchResult { animeInfos = animeInfos, ready = true, qq = qq };
			return stringBuilder.ToString();
		}

		public static string GetWp(string url)
		{
			//http://animewld.club/s.php?url=aHR0cHM6Ly9wYW4uYmFpZHUuY29tL3MvMWxjUlRuLVBCTTRZbl9SUjlUaTNYT0FAQGRpMjQ=

			url = url.Substring(10);
			var index = url.IndexOf(".");
			url = url.Substring(0, url.Length - index);
			var json = JObject.Parse(Encoding.UTF8.GetString(HttpNet.Get("http://www.yxdm.me/getdlist.php?id=" + url)));
			if (json["status"].ToObject<int>() != 0) return "\r\n获取失败";
			StringBuilder stringBuilder = new StringBuilder(255);
			foreach (JObject item in json["data"])
			{
				stringBuilder.Append("\r\n" + item["cnName"]);
				foreach (var item2 in item["list"])
				{
					stringBuilder.Append("\r\n" + item2["title"] + "：" + Url.GetShortUrl("http://animewld.club/s.php?url=" + item2["url"]));
				}
			}
			return stringBuilder.ToString();
		}

		static string GetHTMLTextByMSHtml(string code)
		{
			dynamic obj = Activator.CreateInstance(typeMshtml);
			obj.write("<HTML><BODY><div></div></BODY></HTML>");
			dynamic body = obj.body;
			body.innerHTML = code;
			return body.outerText;
		}

		static string GetBaidu(string url)
		{
			WebHeaderCollection webHeaderCollection = new WebHeaderCollection();
			HttpNet.Get(url, ref webHeaderCollection, null, null, null, 10000, Proxy, null, false, true);
			return webHeaderCollection["Location"];
		}

		public static string GetNewAnimeList(DayOfWeek week)
		{
			// 0 7,1 1
			//https://dilidili.online/
			//WebClient client = new WebClient();
			//client.Headers["User-Agent"] = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36";
			var data = HttpNet.Get("https://dilidili.online/");
			//var data = client.DownloadData("https://dilidili.online/");
			if (data.Length == 0) return "获取失败";
			Console.WriteLine(data.Length);
			var doc = parser.ParseDocument(Encoding.UTF8.GetString(data));
			//wd-panel-2
			var id = "#wd-panel-";
			if (week == 0) id += "7";
			else id += week.ToString("d");
			Console.WriteLine(id);
			StringBuilder sb = new StringBuilder(50);
			StringBuilder sb1 = new StringBuilder(50);
			sb.Append("-----已更新列表-----");
			foreach (var item in doc.QuerySelectorAll(id + " li"))
			{
				var strong = item.QuerySelector("strong");
				var span = item.QuerySelector("span");
				var text = span.TextContent;
				var index = span.TextContent.IndexOfAny(new char[] { '集', '话' });
				if (span.OuterHtml.Contains("red"))
				{
					sb.Append("\n");
					sb.Append(strong.TextContent.Trim());
					sb.Append("   ");
					sb.Append(text.Substring(0, index + 1));
				}
				else
				{
					sb1.Append("\n");
					sb1.Append(strong.TextContent.Trim());
				}
			}
			return sb.ToString() + "\n-----未更新列表-----" + sb1.ToString();
		}

		public static string GetNewAnimeList2(DayOfWeek week)
		{
			var data = HttpNet.Get("http://www.bimibimi.me/");
			if (data.Length == 0) return "获取失败";
			var doc = parser.ParseDocument(Encoding.UTF8.GetString(data));
			var items = doc.QuerySelectorAll("ul.tab-cont__wrap li.item");
			Console.WriteLine(items.Length);
			int index;
			if (week == 0) index = 6;
			else index = int.Parse(week.ToString("d")) - 1;
			Console.WriteLine(index);
			StringBuilder sb1 = new StringBuilder(50);
			sb1.Append("-----已更新列表-----");
			StringBuilder sb2 = new StringBuilder(50);
			sb2.Append("-----未更新列表-----");
			foreach (var item in items[index].QuerySelectorAll("div.item-info"))
			{
				var p = item.LastElementChild;
				if (p.InnerHtml.Contains("fl-new"))
				{
					sb1.Append("\n");
					sb1.Append(item.FirstElementChild.TextContent.Replace("【无修正】", string.Empty));
					sb1.Append("          ");
					sb1.Append(p.TextContent.RemoveEmpty());
				}
				else
				{
					sb2.Append("\n");
					sb2.Append(item.FirstElementChild.TextContent.Replace("【无修正】", string.Empty));
					sb2.Append("          ");
					sb2.Append(p.TextContent.RemoveEmpty());
				}
			}
			return sb1.ToString() + "\n" + sb2.ToString();
		}
	}
}